#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <sys/time.h>
#define MAX_LEN  20
#define SSIDLEN  10
int str_to_number(const char* str);

typedef struct
{
    char ssid[SSIDLEN];
    int command;
}command;

int main()
{
	 int count, ret;
    char message[MAX_LEN];

	int flag_send;
	int sk;
	
    struct sockaddr_in src_addr;    //用于指定本地监听信息
    struct sockaddr_in cli_addr;    //设置客戶端地址信息
    int src_addr_len, cli_addr_len;
    struct in_addr addr;
    struct timeval start, end;
	
    int flag = 0;
    long int tmp = 0;

	/* configure server info:ip  port */
    bzero(&src_addr, sizeof(src_addr));
    src_addr.sin_family = AF_INET;
    src_addr.sin_addr.s_addr = htonl(INADDR_ANY);//htonl(INADDR_ANY);//作为服务器，可能有多块网卡，设置INADDR_ANY，表示绑定一个默认网卡进行监听
    src_addr.sin_port = htons(5050);



    /*  配置client的网络信息 */
    cli_addr.sin_family = AF_INET;
    //cli_addr.sin_addr.s_addr = inet_addr("192.168.153.128");//inet_addr("192.168.153.145");    
    //cli_addr.sin_port = htons(5050);


    src_addr_len = sizeof(src_addr);
    cli_addr_len = sizeof(cli_addr);

    sk = socket(AF_INET, SOCK_DGRAM, 0);
    if (sk < 0)
    {
        printf("socket create failure\n");
        return -1;
    }

    ret = bind(sk, (struct sockaddr*)&src_addr, src_addr_len);
    if (ret < 0)
    {
        printf("socket bind failure\n");
        return -1;
    }
	/* ready buffer info */
    command com1[5];
    com1[0].command = 0;
    strcpy(com1[0].ssid, "zwr");
    memcpy(message, (char*)&com1[0], sizeof(command));
    printf("Waiting for data from sender \n");
    while (1)
    {
        
        count = recvfrom(sk, message, MAX_LEN, 0, (struct sockaddr*)&cli_addr, &cli_addr_len);
        /*if (flag) {
            gettimeofday(&end, NULL);
            tmp = end.tv_sec * 1000000 + end.tv_usec - (start.tv_sec * 1000000 + start.tv_usec);
            if (flag % 2 == 0) {
                //printf("Server收发一个包的时延: %lf 微秒\n", (tmp-1000000) / 2.0); // us
            }
            else {
                printf("Server收发一个包的时延: %lf ms\n\n", tmp / 2000.0); // us
            }
           
          
        } */
          

        if(count==-1)
        {
            printf("receive data failure\n");
            //return -1;
        }
		printf("Receive data success\n");

        flag_send = sendto(sk, message, sizeof(message), 0, (struct sockaddr*)&cli_addr, cli_addr_len);
		while(flag_send == -1){
		printf("Server send failed\n");
		flag_send = sendto(sk, message, sizeof(message), 0, (struct sockaddr*)&cli_addr, cli_addr_len);
		}
        /*gettimeofday(&start, NULL);
        flag++; */  
    }

    close(sk);

    return 0;
}

